package com.greateamd.timetableasy.server;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.greateamd.timetableasy.domain.Event;

public class ServerUtil {

	/**
	 * Return an MD5 hash of the plaintext string, interpretted as UTF-8
	 * @param plaintext
	 * @return String hashtext 
	 */
	public static String md5(String plaintext){

		String hashtext = null;
		
		try {
			
			MessageDigest m = MessageDigest.getInstance("MD5");
			
			m.reset();
			m.update(plaintext.getBytes("UTF-8"));

			byte[] digest = m.digest();
			BigInteger bigInt = new BigInteger(1,digest);
			
			hashtext = bigInt.toString(16);
			// Now we need to zero pad it if you actually want the full 32 chars.
			while(hashtext.length() < 32 ){
				hashtext = "0"+hashtext;
			}
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return hashtext;

	}

	public static void sortStartDateList(final List<Event> events) {
		Comparator<Event> sortStartDate = new Comparator<Event>() {
			
			@Override
			public int compare(Event o1, Event o2) {
				return o1.getStartDate().compareTo(o2.getStartDate());
			}
		};
		Collections.sort(events,sortStartDate);
		
	}
}
